package com.lw.leetcode.hash.b;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 1311. 获取你好友已观看的视频
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/11 9:36
 */
public class WatchedVideosByFriends {


    public static void main(String[] args) {
        WatchedVideosByFriends test = new WatchedVideosByFriends();

        List<List<String>> watchedVideos = new ArrayList<>();
        watchedVideos.add(Arrays.asList("A", "B"));
        watchedVideos.add(Arrays.asList("C"));
        watchedVideos.add(Arrays.asList("B", "C"));
        watchedVideos.add(Arrays.asList("D"));
        int[][] friends = {{1, 2}, {0, 3}, {0, 3}, {1, 2}};
        int id = 0;
        int level = 1;

//        List<List<String>> watchedVideos = new ArrayList<>();
//        watchedVideos.add(Arrays.asList("A", "B"));
//        watchedVideos.add(Arrays.asList("C"));
//        watchedVideos.add(Arrays.asList("B", "C"));
//        watchedVideos.add(Arrays.asList("D"));
//        int[][] friends = {{1,2},{0,3},{0,3},{1,2}};
//        int id = 0;
//        int level = 2;

        List<String> list = test.watchedVideosByFriends(watchedVideos, friends, id, level);
        System.out.println(list);

    }


    public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {
        Set<Integer> set = new HashSet<>();
        set.add(id);
        Set<Integer> item1 = new HashSet<>();
        item1.add(id);
        Set<Integer> item2 = new HashSet<>();
        for (int i = 0; i < level; i++) {
            for (Integer k : item1) {
                int[] friend = friends[k];
                for (int c : friend) {
                    if (set.contains(c)) {
                        continue;
                    }
                    set.add(c);
                    item2.add(c);
                }
            }
            item1.clear();
            item1.addAll(item2);
            item2.clear();
        }
        Map<String, Integer> map = new HashMap<>();
        for (Integer k : item1) {
            List<String> list = watchedVideos.get(k);
            if (list != null) {
                for (String s : list) {
                    map.merge(s, 1, (a, b) -> a + b);
                }
            }
        }
        TreeMap<Integer, Set<String>> treeMap = new TreeMap<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Set<String> orDefault = treeMap.getOrDefault(entry.getValue(), new TreeSet<>());
            orDefault.add(entry.getKey());
            treeMap.put(entry.getValue(), orDefault);
        }
        List<String> list = new ArrayList<>();
        for (Map.Entry<Integer, Set<String>> entry : treeMap.entrySet()) {
            list.addAll(entry.getValue());
        }
        return list;
    }

}
